package com.sduept.nwld.fault.handler;

import java.util.ArrayList;
import java.util.List;

import com.sduept.bigdata.fault.analysis.handler.impl.AbstractCommonHandler;
import com.sduept.bigdata.fault.common.FaultHandlerContext;
import com.sduept.bigdata.fault.common.HandlerContext;
import com.sduept.bigdata.fault.entity.AnalLinefaultEtl;
import com.sduept.bigdata.fault.entity.FaultRecord;
import com.sduept.bigdata.fault.manager.FaultForecastIdentifyManager;
import com.sduept.bigdata.fault.manager.FaultRecordPersistManager;
import com.sduept.bigdata.fault.system.properties.FaultSystemProperties;
import com.sduept.bigdata.ml.domain.LibSvmData;
import com.sduept.bigdata.weather.faultcause.manager.FaultCauseManager;
import com.sduept.utils.SpringContext;

/**
 *故障原因预测
 * @author xu
 */
public class FaultReasonPredictHandler extends AbstractCommonHandler {
	private FaultCauseManager fcm = SpringContext.getBean(FaultCauseManager.class);
	private FaultRecordPersistManager frpm = SpringContext.getBean(FaultRecordPersistManager.class);
	private FaultForecastIdentifyManager fim =  SpringContext.getBean(FaultForecastIdentifyManager.class);
	private FaultSystemProperties pros =  SpringContext.getBean(FaultSystemProperties.class);
	@Override
	public void logic(HandlerContext context) {
		FaultHandlerContext faultContext = (FaultHandlerContext)context;
		FaultRecord faultRecord = faultContext.getCurrentFaultRecord();
		if(faultRecord.getStatus()==1||faultRecord.getSource()!=1||faultRecord.getSource()!=2) {//1为非故障,来源为1和2的去处理
			return;
		}
		faultRecord = setFaultRecordLonAndLat(faultRecord);
		//根据故障生成etl数据
		AnalLinefaultEtl alf = fim.findAnalLinefaultEtlByFaultRecordId(faultRecord.getId());
		if(alf==null) {
			alf =  fcm.faultIdentify(faultRecord.getId(), faultRecord.getEquipment_id(), faultRecord.getFaultTime(),
					faultRecord.getLon() == null ? 0 : faultRecord.getLon().doubleValue(),
					faultRecord.getLat() == null ? 0 : faultRecord.getLat().doubleValue(), 1);
		}
		//TODO  根据关联关系进行匹配etl数据
		if(alf!=null) {
			LibSvmData data = fcm._getLibSvmDate(alf);
			String predictReason =fim.getPredictReason(data,pros.getFaultReasonIdentifyPath());
			if(predictReason==null) {
				predictReason = "其他";
			}
			faultRecord.setFaultForecastReson(predictReason);
			frpm.saveFaultRecordOnly(faultRecord);
		}
	}

	@Override
	public boolean asynExecute() {
		return true;
	}

	/**
	 * 设置经纬度信息
	 * @param fr
	 * @return
	 */
	private FaultRecord setFaultRecordLonAndLat(FaultRecord fr) {
		List<FaultRecord> faults = new ArrayList<>();
		faults.add(fr);
		faults = frpm.setupFaultLonAndLat(faults, true);
		fr = faults.get(0);
		return fr;
	}

}
